import { TagService } from './../tag/tag.service';
import { CategoryService } from './../category/category.service';
import { HttpException, Injectable } from '@nestjs/common';
import { PostsEntity } from './entities/posts.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { CreatePostDto } from './dto/create-post.dot';

export interface PostRo {
  list: PostsEntity[];
  count: number;
}

@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(PostsEntity)
    private readonly postsRepository: Repository<PostsEntity>,
    private readonly categoryService: CategoryService,
    private readonly tagService: TagService
  ) {}

  // 创建文章
  async create(post: CreatePostDto): Promise<PostsEntity> {
    const { title } = post
    if(!title) {
      throw new HttpException('文章标题不能为空', 401)
    } 
    const doc = await this.postsRepository.findOne({ where: { title } })
    if(doc) {
      throw new HttpException('文章标题已存在', 401)
    }

    let { tag, category = 0, status, is_recommend, cover_url } = post

    const categoryDoc = await this.categoryService.findById(category)

    const savePost = await this.postsRepository.create(post)

    return await this.postsRepository.save(savePost)
  }

  // 获取文章列表
  async findAll(query): Promise<PostRo> {
    const qb = await this.postsRepository.createQueryBuilder('post')
    qb.where('1 = 1');
    qb.orderBy('post.create_time', 'DESC');

    const count = await qb.getCount();
    const { pageNo = 1, pageSize = 10, ...params } = query
    qb.limit(pageSize).offset((pageNo - 1) * pageSize);

    const posts = await qb.getMany();
    return { list: posts, count }
  }

  // 获取指定的文章
  async findById(id): Promise<PostsEntity> { 
    return await this.postsRepository.findOne({ where: { id } })
  }

  // 更新文章
  async update(id, post): Promise<PostsEntity> { 
    const existPost = await this.postsRepository.findOne({ where: { id } });
    if(!existPost) {
      throw new HttpException(`id为${id}的文章不存在`, 401);
    }
    const updatePost = this.postsRepository.merge(existPost, post);
    return await this.postsRepository.save(updatePost);
  }

  // 删除文章
  async remove(id) {
    const existPost = await this.postsRepository.findOne({ where: { id } });
    if(!existPost) {
      throw new HttpException(`id为${id}的文章不存在`, 401);
    }
    return await this.postsRepository.remove(existPost);
  }
}
